<template>
	<basic-container>
		<avue-crud :option="option" :data="data" ref="form" v-model="form" :table-loading="loading" :permission="permission"
		 :page="page" @refresh-change="refreshChange" @search-change="searchChange" @search-reset="searchReset"
		 @current-change="currentChange" @size-change="sizeChange" @on-load="onLoad">
			<template slot-scope="{row}" slot="brandLogoUrl">
				<img v-if="row.brandLogoUrl" :src="row.brandLogoUrl" style="width:50px;height:50px;">
			</template>
			<template slot="menuLeft">
				<el-button type="primary" size="small" @click="openDialog">申请品牌</el-button>
			</template>
			<template slot-scope="scope" slot="menu">
				<el-button type="text" icon="el-icon-edit" v-if="scope.row.brandAudit!=1" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="text" icon="el-icon-delete" v-if="scope.row.brandAudit!=1" size="small" @click="rowDelList(scope.row)">删除</el-button>
			</template>
		</avue-crud>
		<el-dialog :title="title" ref="dialoghome" :visible.sync="dialogVisible" width="60%" :before-close="closeDialog"
		 :close-on-click-modal="true">
			<avue-form ref="form" v-model="obj" :option="optionAdd" @submit="addrecurseData">
				<template slot-scope="scope" slot="brandLogoUrl">
					<div class="upload" style="width: 100%;position: relative;">
						<el-col style="width: calc(100% - 158px);">
							<el-input style="margin-right: 0.2rem;" readonly @focus="$refs.selFile.open()" placeholder="请选择品牌图片" v-model="obj.brandLogoUrl" />
						</el-col>
						<el-col style="width: 38px;height: 38px;overflow: hidden;margin-left: 15px;background: #f5f6f7;text-align: center;">
							<el-image v-if="obj.brandLogoUrl" @click="$refs.selFile.open()" fit="contain" :src="obj.brandLogoUrl" width="38" height="38">
								<div slot="error" class="image-slot">
									<i class="el-icon-picture-outline"></i>
								</div>
							</el-image>
						</el-col>
						<el-col style="width: 90px;margin-left: 15px;">
							<el-button size="small" type="primary" @click="$refs.selFile.open()">上传图片</el-button>
						</el-col>
					</div>
				</template>
				<template slot-scope="scope" slot="menuForm">
					<el-button @click="closeDialog">取消</el-button>
				</template>
			</avue-form>
			<selFile ref="selFile" @callback="selFileCallBack" albumCode="store" dialogTitle="选择图片" selectType="radio"
			 selMaxWidth="300px" selMaxHeight="300px"></selFile>
		</el-dialog>
	</basic-container>
</template>

<script>
	import selFile from '@/components/file/selFile'
	import uploadPic from '@/components/file/uploadPic';
	import {
		getList,
		remove,
		add,
		update
	} from "@/api/base/goods/seller/brand";
	import {
		mapGetters
	} from "vuex";
	import {
		validateUpperCase
	} from '@/util/validate';
	import {
		testSort,
		validateFormat
	} from '@/util/util';
	import {isWord} from '@/util/rej'
	var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
	export const bannerTitle = (rule, value, callback) => {
		value = value.trim();
		if (!value) {
			callback(new Error("请输入标题"))
		} else if (value.length < 2 || value.length > 10) {
			callback(new Error('字数请保持在2~10个'));
		} else {
			callback();
		}
	}
	export default {
		data() {
			return {
				btnloading: false,
				title: '申请品牌',
				dialogVisible: false,
				form: {},
				query: {},
				// 新增资源
				addData: [],
				loading: true,
				rolesTree: [],
				rolesKeys: [],
				// 申请列表数据
				dataList: [],
				box: false,
				activeName: 'first',
				pageTotal:false,
				page: {
					pageSize: 10,
					currentPage: 1,
					total: 0
				},
				data: [],
				obj: {},
				optionAdd: {
					labelWidth: 150,
					emptyBtn: false,
					column: [{
						label: "品牌名称",
						prop: "brandName",
						row: true,
						minlength: 2,
						maxlength: 10,
						span: 18,
						rules: [{
							required: true,
							validator: bannerTitle,
							trigger: 'blur'
						},{
							required:true,
							validator:validateFormat,
							trigger:'blur'
						}]
					}, {
						label: "首字母（大写）",
						prop: "firstWord",
						row: true,
						maxlength: 1,
						span: 18,
						rules: [{
							validator: isWord,
							trigger: "blur"
						}]
					}
					// , {
					// 	label: "类别",
					// 	prop: "brandCategoryName",
					// 	row: true,
					// 	minlength: 1,
					// 	maxlength: 6,
					// 	span: 18,
					// 	rules: [{
					// 		required: true,
					// 		message: "请输入类别",
					// 		trigger: "blur"
					// 	}]
					// }
						, {
						label: "品牌图片",
						prop: "brandLogoUrl",
						row: true,
						formslot: true,
						span: 18,
					}, {
						label: "排序",
						prop: "brandSequence",
						row: true,
						clearable: false,
						span: 18,
						rules: [{
							required: true,
							message: "请输入排序",
							trigger: "change"
						},
						{
							validator: testSort,
							trigger: 'blur'
						},
						]
					}, {
						label: "申请备注",
						prop: "brandRemark",
						row: true,
						type: 'textarea',
						minRows: 2,
						maxRows: 4,
						maxlength: 50,
						span: 18,
						rules: [{
							message: "请输入申请备注",
							trigger: "blur"
						}]
					}, ],
				},
				option: {
					size: 'mini',
					excelBtn: false,
					tip: false,
					border: true,
					index: true,
					addBtn: false,
					editBtn: false,
					selection: false,
					delBtn: false,
					viewBtn: false,
					rowKey: 'id',
					align: 'center',
					menuWidth: 150,
					column: [{
							label: "品牌名称",
							prop: "brandName",
							search: false,
							width: 150,
						}, {
							label: "排序",
							prop: "brandSequence",
							type: 'number',
							// sortable: true
						}, {
							label: "首字母",
							prop: "firstWord",
							searchGutter: '20',
							searchSpan: 6,
						}, {
							label: "品牌图片",
							prop: "brandLogoUrl",
							slot: true,
						},
						{
							label: "申请备注",
							prop: "brandRemark",
							width: 210
						},
						{
							label: "审核状态",
							prop: "brandAudit",
							type: 'select',
							search: false,
							dicData: Dict.STORE_BRAND_STATUS,
							width: 120,
						}
					]
				},
			};
		},
		computed: {
			...mapGetters(["permission", 'userInfo', 'dictionariy']),
			permissionList() {
				return {

				};
			},
		},
		components: {
			selFile,
			uploadPic,
		},
		watch: {
			'dialogVisible'(val) {
				if (!val) {
					this.$nextTick(() => {
						this.$refs["formRef"].resetFields();
						this.addForm = {
							brandName: '',
							firstWord: '',
							brandCategoryName: '',
							brandLogoUrl: '',
							brandSequence: 0,
							brandRemark: '',
						};
					})
					this.btnloading = false;
				}
			},
			pageTotal(val){
				if (val) {
					//针对删除数据用的所以this.page.total需要减一
					this.page.total -= 1;
					//当页面总条数 = （当前页数-1）*当前页条数，currentPage减1，重新获取列表
					if (this.page.total == (this.page.currentPage - 1) * this.page.pageSize && this.page.total - 1 != 0) {
						this.page.currentPage -= 1;
						//获取列表数据
						this.onLoad(this.page);
					} else {
						//获取列表数据
						this.onLoad(this.page);
					}
				}
			}
		},
		methods: {
			// 选择图片
			selFileCallBack(obj) {
				this.$nextTick(() => {
					this.obj.brandLogoUrl = obj[0];
				})
			},
			// 弹窗新增确定按钮
			addrecurseData(btnloading,done) {
				this.btnloading = true;
				if (this.obj.id) { //修改
					if (this.obj.brandAudit == '-1') {
						this.obj.brandAudit = '0'
					}
					update(this.obj).then((res) => {
						if (res.data.code == 200) {
							setTimeout(() => {
								this.btnloading = false;
							}, 1000)
							done();
							this.onLoad(this.page);
							this.$message({
								type: "success",
								message: "修改品牌成功!"
							});
							this.dialogVisible = false;
							this.closeDialog()
							setTimeout(() => {
								this.btnloading = false;
							}, 1000)
						}
					})
				} else { //新增
					if (this.obj.brandName == ''  || this.obj.brandCategoryName == '') {
						this.$message({
							type: "error",
							message: "请输入完整品牌的信息!"
						});
					} else {
						add(this.obj).then((res) => {
							if (res.data.code == 200) {
								this.onLoad(this.page);
								this.$message({
									type: "success",
									message: "添加品牌成功!"
								});
								done();
								this.$nextTick(() => {
									this.closeDialog()
								})
								setTimeout(() => {
									this.btnloading = false;
								}, 1000)
								this.dialogVisible = false;
								this.obj = {}
							}

						})
					}
				}
			},
			openDialog() {
				this.title = "申请品牌";
				this.dialogVisible = true;
				this.$nextTick(()=>{
					this.$refs["form"].clearValidate();
				});
			},
			closeDialog() {
				this.dialogVisible = false;
				this.$refs.form.resetForm();
				this.$nextTick(()=>{
					this.$refs["form"].clearValidate();
				});
			},
			edit(row) {
				this.title = '编辑品牌'
				this.obj = row
				this.dialogVisible = true;
				this.$nextTick(()=>{
					this.$refs["form"].clearValidate();
				});
			},
			searchReset() {
				this.query = {};
				this.onLoad(this.page);
			},
			searchChange(params,done) {
				this.page.currentPage = 1
				this.query = params;
				this.onLoad(this.page, params,done);
			},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
			},
			refreshChange() {
				this.onLoad(this.page);
			},
			rowDelList(row) {
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(row.id);
					})
					.then(() => {
						this.pageTotal = true;
						this.$message({
							type: "success",
							message: "删除成功!"
						});
					});
			},
			onLoad(page, params = {},done) {
				this.loading = true;
				getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
					if(done){
						done();
					}
					this.loading = false;
					const data = res.data;
					this.page.total = data.count;
					this.data = data.data;
				});
				this.pageTotal = false;
			},
		}
	};
</script>

<style scoped>
	.upload {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
</style>
